//
// Created by summer1988 on 2024/1/7.
//

#import <CaptainHook/CaptainHook_monkeydev.h>
#import "DYCallAManager.h"
#import "GCDWebServer/GCDWebServerResponse.h"
#import "GCDWebServer/GCDWebServerURLEncodedFormRequest.h"
#import "GCDWebServer/GCDWebServer.h"
#import "GCDWebServer/GCDWebServerDataResponse.h"
#import "NSObject+YYModel.h"


@interface DYCallAManager ()
@property(nonatomic, retain) GCDWebServer *webServer;
@end

@implementation DYCallAManager {

}

+ (instancetype)sharedInstance {
    static dispatch_once_t token;
    static DYCallAManager *instance;

    dispatch_once(&token, ^{
        instance = [DYCallAManager new];
        [instance initWebServer];
    });
    return instance;
}

- (void)initWebServer {
    @autoreleasepool {
        WS(weakSelf);
        _webServer = [GCDWebServer new];
        [_webServer addDefaultHandlerForMethod:@"POST"
                                  requestClass:[GCDWebServerURLEncodedFormRequest class]
                             asyncProcessBlock:^(
                                     GCDWebServerURLEncodedFormRequest *request,
                                     GCDWebServerCompletionBlock completionBlock
                             ) {
                                 NSDictionary *res = [weakSelf handleWebRequest:request];
                                 GCDWebServerResponse *response = [GCDWebServerDataResponse responseWithJSONObject:res];
                                 [response setValue:@"*" forAdditionalHeader:@"Access-Control-Allow-Origin"];
                                 [response setValue:@"no-cache" forAdditionalHeader:@"Cache-Control"];
                                 completionBlock(response);
                             }];
    }
}

- (void)startWebServer {
    @autoreleasepool {
        [_webServer startWithPort:8808 bonjourName:@"0.0.0.0"];
    }
}

- (NSDictionary *)handleWebRequest:(GCDWebServerURLEncodedFormRequest *)request {
    @autoreleasepool {
        NSString *path = request.path;
        int timeout = [request.arguments[@"timeout"] intValue];
        if (!timeout) {
            timeout = 25;
        }
        NSString *token = request.arguments[@"x-tt-token"];
        CHLogSource(@"==> request here: %@, %d, %@", request.path, timeout, request.arguments);
        if ([path containsString:@"/search/shop"]) {
            NSString *keyword = request.arguments[@"keyword"];
            int cursor = [request.arguments[@"cursor"] intValue];
            if (!keyword || keyword.length < 2) {
                return @{@"code": @-1, @"message": @"关键词不符合标准"};
            }
            return [self searchShopWithKeyword:keyword
                                    withCursor:cursor
                           withSearchRequestId:request.arguments[@"search_request_id"]
                                  withSearchId:request.arguments[@"search_id"]
                                     withToken:token
                                   withTimeout:timeout];
        } else if ([path containsString:@"/share/command/trans"]) {
            NSString *command = request.arguments[@"command"];
            if (!command || command.length < 2) {
                return @{@"code": @-1, @"message": @"命令不符合标准"};
            }
            return [self transShareProductCommand:command
                                        withToken:token
                                      withTimeout:timeout];
        } else if ([path containsString:@"/product/shop_sec_id"]) {
            NSString *productId = request.arguments[@"product_id"];
            if (!productId || productId.length < 2) {
                return @{@"code": @-1, @"message": @"商品ID不符合标准"};
            }
            return [self getShopIdWithProductId:productId
                                      withToken:token
                                    withTimeout:timeout];
        } else if ([path containsString:@"/shop/detail2"]) {
            NSString *shopSecId = [request.arguments[@"shop_sec_id"] copy];
            NSString *shopId = [request.arguments[@"shop_id"] copy];
            if (!shopId && !shopSecId) {
                return @{@"code": @-1, @"message": @"店铺ID不符合标准"};
            }
            return [self getShopDetail2WithSecId:shopSecId
                                      withShopId:shopId
                                       withToken:token
                                     withTimeout:timeout];
        } else if ([path containsString:@"/shop/detail"]) {
            NSString *shopSecId = [request.arguments[@"shop_sec_id"] copy];
            NSString *shopId = [request.arguments[@"shop_id"] copy];
            if (!shopId && !shopSecId) {
                return @{@"code": @-1, @"message": @"店铺ID不符合标准"};
            }
            return [self getShopDetailWithSecId:shopSecId
                                     withShopId:shopId
                                      withToken:token
                                    withTimeout:timeout];
        } else if ([path containsString:@"/shop/phone"]) {
            NSString *shopSecId = [request.arguments[@"shop_sec_id"] copy];
            NSString *shopId = [request.arguments[@"shop_id"] copy];
            if (!shopId && !shopSecId) {
                return @{@"code": @-1, @"message": @"店铺ID不符合标准"};
            }
            return [self getShopPhoneWithSecShopId:shopSecId
                                        withShopId:shopId
                                         withToken:token
                                       withTimeout:timeout];
        } else if ([path containsString:@"/search/product"]) {
            NSString *keyword = request.arguments[@"keyword"];
            int cursor = [request.arguments[@"cursor"] intValue];
            if (!keyword || keyword.length < 2) {
                return @{@"code": @-1, @"message": @"关键词不符合标准"};
            }
            return [self searchProductWithKeyword:keyword
                                    withCursor:cursor
                           withSearchRequestId:request.arguments[@"search_request_id"]
                                  withSearchId:request.arguments[@"search_id"]
                                     withToken:token
                                   withTimeout:timeout];
        }
        return @{@"code": @-1, @"message": @"请求路径不符合标准"};
    }
}

- (NSDictionary *)searchShopWithKeyword:(NSString *)keyword
                             withCursor:(int)cursor
                    withSearchRequestId:(NSString *)searchRequestId
                           withSearchId:(NSString *)searchId
                              withToken:(NSString *)token
                            withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{
                @"search_scene": @"douyin_search",
                @"enter_from": @"search_order_center",
                @"count": @"10",
//                @"device_score": @"10.0985",
                @"query_correct_type": @"1",
                @"should_switch_network_loader": @"1",
                @"search_source": @"ecommerce_subtab_switch",
                @"cursor": @(cursor),
                @"enter_from_second": @"xtab_homepage__homepage_top_tab",
                @"keyword": keyword,
                @"hot_search": @"0"
        } mutableCopy];
        if (searchRequestId) {
            params[@"search_request_id"] = searchRequestId;
        }
        if (searchId) {
            params[@"search_id"] = searchId;
        }
        if (token) {
            params[@"x-tt-token"] = token;
        }

        dispatch_async(queue, ^{
            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://ecom5-normal-lq.ecombdapi.com/aweme/v2/search/store/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret) {
            return @{@"code": @0, @"data": ret};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"搜索店铺失败"};
        }
    }
}

- (NSDictionary *)searchProductWithKeyword:(NSString *)keyword
                             withCursor:(int)cursor
                    withSearchRequestId:(NSString *)searchRequestId
                           withSearchId:(NSString *)searchId
                              withToken:(NSString *)token
                            withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{
                @"address_book_access": @"0",
                @"client_engine_extra": @"{\"pitaya_upload_info\":\"{\\\"sar_liveroom\\\": {}}\"}",
                @"count": @"8",
                @"current_page": @"order_center",
                @"cursor": @(cursor),
                @"device_score": @"10.0985",
                @"ecom_scene_id": @"1099,1031",
                @"ecom_theme": @"light",
                @"enter_from": @"search_order_center",
                @"enter_from_second": @"xtab_homepage__homepage_top_tab",
//                @"extra": @"{\"productId\":\"3640372944410163056\",\"search_ecom_params\":\"{\\\"words_type\\\":\\\"qrec_hot\\\"}\",\"previous_page\":\"search_page\",\"recommend_word_id\":\"\",\"recommend_word_session_id\":\"\",\"enter_method\":\"normal_search\",\"recommend_tab_gid\":\"7319011518559849765\",\"shop_id\":[54507770]}",
//                @"from_group_id": @"7319011518559849765",
                @"large_font_mode": @"0",
                @"location_access": @"2",
//                @"lynx_ssr_props": @"{\"screenWidth\":414,\"fontScale\":1,\"screenHeight\":896,\"devicePlatform\":\"ios\"}",
                @"need_personal_recommend": @"1",
                @"no_trace_search_switch": @"off",
                @"query": keyword,
                @"query_correct_type": @"1",
                @"request_type": @"1",
                @"search_channel": @"search_order_center",
                @"search_filter": @"1",
                @"search_scene": @"douyin_search",
                @"search_source": @"search_history",
                @"shown_count": @"0"
        } mutableCopy];
        if (searchRequestId) {
            params[@"search_request_id"] = searchRequestId;
        }
        if (searchId) {
            params[@"search_id"] = searchId;
        }
        if (token) {
            params[@"x-tt-token"] = token;
        }

        dispatch_async(queue, ^{
            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://ecom5-normal-lq.ecombdapi.com/aweme/v2/shop/search/aggregate/shopping/stream/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *err) {
                                                               ret = result;
                                                               error = err;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret) {
            return @{@"code": @0, @"data": ret};
        } else {
            if (error != nil && error.userInfo) {
                NSData *data = error.userInfo[@"AWENetworkRespnseObjectKey"];
                CHLogSource(@"==> ttttt => %@", error.userInfo);
                if (data) {
                    return @{@"code": @0, @"data": [NSString stringWithUTF8String:static_cast<const char *>(data.bytes)]};
                }
            }
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"搜索商品失败"};
        }
    }
}

- (NSDictionary *)transShareProductCommand:(NSString *)command
                                 withToken:(NSString *)token
                               withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;

        NSMutableDictionary *params = [@{
                @"command": command
        } mutableCopy];
        if (token) {
            params[@"x-tt-token"] = token;
        }
        dispatch_async(queue, ^{
            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://aweme.snssdk.com/aweme/v2/platform/share/command/trans/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret) {
            if (ret[@"command_gen_scene"]) {
                NSDictionary *real = [NSJSONSerialization JSONObjectWithData:[ret[@"command_gen_scene"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                if (real && real[@"carrier_dep_info"]) {
                    NSDictionary *scene = [NSJSONSerialization JSONObjectWithData:[real[@"carrier_dep_info"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                    return @{@"code": @0, @"data": scene};
                }
                return @{@"code": @0, @"data": real};
            }
            return @{@"code": @0, @"data": ret};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"转换失败"};
        }
    }
}

- (NSDictionary *)getShopIdWithProductId:(NSString *)productId
                               withToken:(NSString *)token
                             withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{
                @"bff_type": @"1",
                @"channel_type": @"0",
                @"enter_from": @"order_merge_page",
                @"gps_on": @"0",
                @"height": @"750",
                @"promotion_id_list[]": productId,
                @"promotion_ids": productId,
                @"shop_avatar_shrink": @"162_162"
        } mutableCopy];
        if (token) {
            params[@"x-tt-token"] = token;
        }

        dispatch_async(queue, ^{

            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://ecom5-normal-lq.ecombdapi.com/aweme/v2/shop/promotion/pack/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret) {
            if (ret[@"promotion_v3"] && ret[@"promotion_v3"][@"shop_float_entry"][@"vo"][@"meta"][@"business_meta"]) {
                NSString *infoString = [ret yy_modelToJSONString];
                NSRange secRange = [infoString rangeOfString:@"sec_shop_id=(.*?)&" options:NSRegularExpressionSearch];
                NSString *secShopId;
                if (secRange.location != NSNotFound) {
                    secShopId = [infoString substringWithRange:secRange];
                    secShopId = [[secShopId componentsSeparatedByString:@"="][1] stringByReplacingOccurrencesOfString:@"&" withString:@""];
                }
                if (secShopId) {
                    return @{@"code": @0, @"data": @{@"secShopId": secShopId}};
                } else {
                    return @{@"code": @-1, @"message": @"获取店铺ID失败"};
                }
            }
            return @{@"code": @0, @"data": ret};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"获取店铺ID失败"};
        }
    }
}

- (NSDictionary *)getShopDetailWithSecId:(NSString *)secId
                              withShopId:(NSString *)shopId
                               withToken:(NSString *)token
                             withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{
                @"live_request_from_jsb": @"1",
                @"biz_param": [NSString stringWithFormat:@"{\"sec_shop_id\": \"%@\"}", secId],
                @"block_code": @"shop_detail_info"
        } mutableCopy];
        if (token) {
            params[@"x-tt-token"] = token;
        }
        if (secId) {
            params[@"biz_param"] = [NSString stringWithFormat:@"{\"sec_shop_id\": \"%@\"}", secId];
        }
        if (shopId) {
            params[@"biz_param"] = [NSString stringWithFormat:@"{\"shop_id\": %@}", shopId];
        }

        CHLogSource(@"==> shop id sec id: %@, %@", shopId, params);

        dispatch_async(queue, ^{

            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://ecom5-normal-lq.ecombdapi.com/sws/block/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret && [ret[@"code"] intValue] == 0) {
            NSDictionary *data = ret[@"block"];
            if (data[@"module_list"]) {
                NSMutableDictionary *realData = [NSMutableDictionary dictionaryWithDictionary:data];
                for (NSDictionary *item in data[@"module_list"]) {
                    NSDictionary *itemData = [NSJSONSerialization JSONObjectWithData:[item[@"data"] dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
                    realData[item[@"name"]] = itemData;
                }
                [realData removeObjectForKey:@"module_list"];
                return @{@"code": @0, @"data": realData};
            }
            return @{@"code": @0, @"data": data};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"获取店铺详情失败"};
        }
    }
}
// https://ecom5-normal-lq.ecombdapi.com/shop/home/info/

- (NSDictionary *)getShopDetail2WithSecId:(NSString *)secId
                               withShopId:(NSString *)shopId
                                withToken:(NSString *)token
                              withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{

        } mutableCopy];
        if (token) {
            params[@"x-tt-token"] = token;
        }
        if (secId) {
            params[@"sec_shop_id"] = secId;
        }
        if (shopId) {
            params[@"shop_id"] = shopId;
        }

        dispatch_async(queue, ^{

            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://ecom5-normal-lq.ecombdapi.com/shop/home/info/"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret && [ret[@"code"] intValue] == 0) {
            return @{@"code": @0, @"data": ret};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"获取店铺详情失败"};
        }
    }
}


- (NSDictionary *)getShopPhoneWithSecShopId:(NSString *)secId
                                 withShopId:(NSString *)shopId
                                  withToken:(NSString *)token
                                withTimeout:(int)timeout {
    @autoreleasepool {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        __block NSDictionary *ret;
        __block NSError *error;
        NSMutableDictionary *params = [@{
        } mutableCopy];
        if (token) {
            params[@"x-tt-token"] = token;
        }
        if (secId) {
            params[@"sec_shop_id"] = secId;
        }
        if (shopId) {
            params[@"shop_id"] = shopId;
        }

        dispatch_async(queue, ^{

            [NSClassFromString(@"AWENetworkService") getWithURLString:@"https://pigeon5-normal-lq.ecombdapi.com/appclient/getPhone"
                                                               params:params
                                                     needCommonParams:YES
                                                           completion:^(NSDictionary *result, NSError *error) {
                                                               ret = result;
                                                               error = error;
                                                               dispatch_semaphore_signal(semaphore);
                                                           }];
        });

        dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * timeout));
        if (ret && [ret[@"code"] intValue] == 0) {
            return @{@"code": @0, @"data": ret[@"data"]};
        } else {
            return @{@"code": @-1, @"message": error ? error.localizedDescription : @"获取店铺号码失败"};
        }
    }
}

- (void)describePB:(Class)pb {
    @autoreleasepool {
        if ([pb respondsToSelector:@selector(descriptor)]) {
            GPBDescriptor *descriptor = [pb descriptor];
            if (descriptor) {
                for (GPBFieldDescriptor *field in descriptor.fields) {
                    CHLogSource(@"==> field: %d %@ = %d", field.dataType, field.name, field.number);
                }
            }
        }
    }
}

@end